package com.tool.engine.export.mertics.time;

import com.tool.engine.export.mertics.system.MemorySize;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.function.UnaryOperator;

@Data
public class ExecutionTime {

    private long totalCount;

    private long minExecutionTime;

    private long maxExecutionTime;

    private long avgExecutionTime;

    private long totalExecutionTime;

    public ExecutionTime(long totalCount, long minExecutionTime, long maxExecutionTime, long avgExecutionTime, long totalExecutionTime) {
        this.totalCount = totalCount;
        this.minExecutionTime = minExecutionTime;
        this.maxExecutionTime = maxExecutionTime;
        this.avgExecutionTime = avgExecutionTime;
        this.totalExecutionTime = totalExecutionTime;
    }

    public ExecutionTime() {
        this.totalCount = 0;
        this.minExecutionTime = Long.MAX_VALUE;
        this.maxExecutionTime = 0;
        this.avgExecutionTime = 0L;
        this.totalExecutionTime = 0L;
    }

    public UnaryOperator<ExecutionTime> createFunction(long costTime) {
        return old -> {
            if (Objects.isNull(old)) {
                old = new ExecutionTime();
            }
            long total = old.getTotalCount() + 1;
            long totalTime = old.getTotalExecutionTime() + costTime;
            long max = Math.max(old.getMaxExecutionTime(), costTime);
            long min = Math.min(old.getMinExecutionTime(), costTime);
            long avg = new BigDecimal(totalTime).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).longValue();
            return new ExecutionTime(total, min, max, avg, totalTime);

        };
    }
}
